﻿using System;
using System.Web;
using System.Web.Mvc;

namespace XRM.Security.WebUI.Helpers
{
    public static class CookieHelper
    {
        public static string GetCookie( this HtmlHelper html, string name )
        {
            return GetCookie( html.ViewContext.HttpContext.Request, name );
        }

        public static string GetCookie( this Controller controller, string name )
        {
            return GetCookie( controller.Request, name );
        }

        private static string GetCookie( HttpRequestBase request, string name )
        {
            var cookie = request.Cookies[name];
            if ( cookie == null )
            {
                return null;
            }

            return cookie.Value;
        }

        public static void AddCookie( this Controller controller, string name, string path, string value )
        {
            HttpCookie cookie = new HttpCookie( name );
            cookie.Path = path;
            cookie.Value = value;

            controller.HttpContext.Response.Cookies.Add( cookie );
        }

        public static void RemoveCookie( this Controller controller, string name, string path )
        {
            RemoveCookie( controller.HttpContext.Response, name, path );
        }

        public static void RemoveCookie( this HttpResponseBase response, string name, string path )
        {
            HttpCookie cookie = new HttpCookie( name );
            cookie.Path = path;
            cookie.Expires = new DateTime( 1999, 10, 12 );

            response.Cookies.Remove( name );
            response.Cookies.Add( cookie );
        }
    }
}